package tsj.ai.alibaba.data.analysis.service.datasource;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tsj.ai.alibaba.data.analysis.entity.AgentDatasource;
import tsj.ai.alibaba.data.analysis.mapper.AgentDatasourceMapper;
import tsj.ai.alibaba.data.analysis.mapper.DatasourceMapper;
import tsj.ai.alibaba.data.analysis.entity.Datasource;

import java.util.List;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-11-14 14:11:15
 */
@Slf4j
@Service
@AllArgsConstructor
public class DatasourceServiceImpl  implements DatasourceService {

    @Autowired
    private DatasourceMapper datasourceMapper;
    @Autowired
    private AgentDatasourceMapper agentDatasourceMapper;

    @Override
    public Datasource getDatasourceById(Long id) {
        return datasourceMapper.selectById(id);
    }

    @Override
    public Datasource getActiveDatasourceByAgentId(Integer agentId) {
        AgentDatasource agentDatasource = getAgentDatasource(agentId).stream()
                .filter(a -> a.getIsActive() == 1)
                .findFirst()
                .orElse(null);
        if (agentDatasource == null) {
            return null;
        }
        return agentDatasource.getDatasource();
    }

    public List<AgentDatasource> getAgentDatasource(Integer agentId) {
        List<AgentDatasource> adentDatasources = agentDatasourceMapper.selectByAgentIdWithDatasource(agentId);

        // Manually fill in the data source information (since MyBatis Plus does not
        // directly support complex join query result mapping)
        for (AgentDatasource agentDatasource : adentDatasources) {
            if (agentDatasource.getDatasourceId() != null) {
                Datasource datasource = datasourceMapper.selectById(Long.parseLong(agentDatasource.getDatasourceId()+""));
                agentDatasource.setDatasource(datasource);
            }
        }

        return adentDatasources;
    }
}
